package com.example.pikachu.mybatis;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

@Configuration
public class autoFillHandler implements MetaObjectHandler {

    private String CREATE_TIME_KEY = "createTime";

    private String MODIFY_TIME_KEY = "modifyTime";

    @Override
    public void insertFill(MetaObject metaObject) {
        fillFiledUseCurrentDate(metaObject, CREATE_TIME_KEY);
        fillFiledUseCurrentDate(metaObject, MODIFY_TIME_KEY);
    }

    private static void fillFiledUseCurrentDate(MetaObject metaObject, String filedName) {
        Object modifyTime =  metaObject.getValue(filedName);
        if(modifyTime == null){
            metaObject.setValue(filedName,new Date());
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        fillFiledUseCurrentDate(metaObject, MODIFY_TIME_KEY);
    }
}
